package com.siyuanren.gcocp.util;

import com.siyuanren.gcocp.annotation.ValidCheck;
import com.siyuanren.gcocp.common.exception.BaseException;

import java.lang.reflect.Field;

/**
 * Created by   anxing
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.util
 * Date         2018/4/18
 * Time         11:21
 * Description 判读参数是否有效util
 * @Valicheck  依赖注解, 只有被正确注解的成员变量才能判断
 */
public class VaildUtil {

    public static void check(Object object) throws Exception {
        if (object == null) {
            throw BaseException.PARAMETER_ERROR;
        }
        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            ValidCheck check = field.getAnnotation(ValidCheck.class);
            if (check != null) {
                // 判断参数是否可以为空,如果为空则不进行检查.
                if (!check.nullable()) {
                    field.setAccessible(true);
                     Object fv = field.get(object);
                     if (fv == null) {
                         String message = field.getName() + "参数不能为空";
                         if (!"".equalsIgnoreCase(check.errMsg())) { // 如果配置自定义提示,则用自定义提示信息
                             message = check.errMsg();
                         }
                         throw new BaseException(1000, message);
                     }
                }
            }
        }
    }
}
